package com.andnnl.guava;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.util.concurrent.Executors;

/**
 * Created by chenss on 2019/9/20.
 */
public class FutureTest1 {


    public static void main(String[] args) {

        // 创建线程池
        ListeningExecutorService listeningExecutorService = MoreExecutors.
                listeningDecorator(Executors.newFixedThreadPool(10));
        FutureCallBackTask callback = new FutureCallBackTask();
        // 记录开始时间
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 2; i++) {
            // 一个耗时的任务
            ListenableFuture<Boolean> listenableFuture = listeningExecutorService.submit(() -> {
                System.out.println("start...");
                //模拟耗时5s
                Thread.sleep(2000);
                System.out.println("end...");
                return true;
            });
            // 注册回调事件
            Futures.addCallback(listenableFuture, callback, listeningExecutorService);
        }
//        listeningExecutorService.shutdown();
        // 记录结束时间
        Long end = System.currentTimeMillis();
        // 执行时间
        System.out.println("线程执行结束了，耗时=" + (end - start) + "毫秒");

    }

}
